﻿using System;
using System.Collections.Generic;
using System.Text;
using Medianamik.Core.DAL.SQL;
using Medianamik.Core.Interfaces;

namespace Medianamik.Core.DAL
{
    public class GetNodesCommandBuilder
    {
        private ParameterNameGenerator _paramGenerator = new ParameterNameGenerator();
        private JoinNameGenerator _joinGenerator = new JoinNameGenerator();

        protected SubSonic.DataProvider Provider
        {
            get;
            private set;
        }

        public GetNodesCommandBuilder(SubSonic.DataProvider pSubsonicDataProvider)
        {
            Provider = pSubsonicDataProvider;
        }


        public SubSonic.QueryCommand Build(IQueryDefinition pQueryDef, bool pLazyLoadProperties, bool withDeleted)
        {
            IEnumerable<IParameter> queryParams;

            var rowNumberQuery = new RowNumberQueryBuilder(pQueryDef, _paramGenerator, _joinGenerator).Build(out queryParams, withDeleted);
            var pagedQuery = new PagedQuery(rowNumberQuery, pQueryDef.SkipCount, pQueryDef.TakeCount);

            var finalQuery = new StringBuilder()
            .AppendLine(" DECLARE @t TABLE ( rownum INT, NodeId UNIQUEIDENTIFIER )")
            .AppendLine(" INSERT INTO @t ")
            .Append(pagedQuery.ToSQL());

            //Requete pour les Nodes
            finalQuery.AppendLine(@" SELECT  n.* from @t t 
                inner join medianamik_node n on n.nodeid = t.nodeid 
                order by t.rownum ");

            //Requete pour les NodeInstances
            finalQuery.AppendLine(@" SELECT  ni.*
                FROM    medianamik_nodeinstance ni 
                INNER JOIN @t AS t ON ni.nodeid = t.nodeid");

            if (!pLazyLoadProperties)
            {
                //Requete pour les NodePropertyValues
//                finalQuery.AppendLine(@" SELECT  v.*
//                    FROM medianamik_nodepropertyvalue v 
//                    inner join @t as t on v.nodeid = t.nodeid
//                    WHERE  v.endrevision is null ");
                throw new NotImplementedException("EagerLoadProperties");
            }


            var command = new SubSonic.QueryCommand(finalQuery.ToString(), Provider.Name);

            foreach (var p in queryParams)
            {
                command.Parameters.Add(p.Name, p.Value);
            }

            return command;
        }
    }
}


